from wtforms import StringField, PasswordField
from wtforms.validators import ValidationError, Length, DataRequired, EqualTo
from app.form.base_form import BaseForm
from app.models import BlogUser


class RegisterForm(BaseForm):
    """用户注册校验
    """
    username = StringField(validators=[
        DataRequired('用户名不允许为空'),
        Length(4, 32, message="用户名4~32个字符")
    ])
    password = PasswordField(validators=[
        DataRequired('密码不允许为空'),
        Length(6, 32, message="密码长度6~32个字符")
    ])
    password_confirm = PasswordField(validators=[
        DataRequired('确认密码不允许为空'),
        Length(6, 32, message="密码长度6~32个字符"),
        EqualTo("password", message="密码和确认密码不一致")
    ])

    def validate_username(form, field):
        """验证用户名是否存在"""
        user = BlogUser.query.filter_by(username=field.data).first()
        if user is not None:
            raise ValidationError(message="用户名已存在")
